package com.lujianfei.mqtt.map

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.view.Display
import android.view.Surface
import android.view.WindowManager
import com.tencent.tencentmap.mapsdk.maps.model.Marker
import kotlin.math.abs


/**
 * @Author: wn
 * @Date: 2024/4/19 17:13
 * @Description: 定位标跟随手机朝向移动 -- 获取手机sensor角度值并过滤
 * 实例化 后 传递 marker 且 定位点需要自定义
 */
class SensorEventHelper(context: Context) : SensorEventListener {
  private val mSensorManager: SensorManager
  private val mSensor: Sensor
  private var lastTime: Long = 0
  private val TIME_SENSOR = 100
  private var mAngle = 0f
  private val mContext: Context
  private var mMarker: Marker? = null

  init {
    mContext = context
    mSensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
    mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION)
  }

  fun registerSensorListener() {
    mSensorManager.registerListener(
      this, mSensor,
      SensorManager.SENSOR_DELAY_NORMAL
    )
  }

  fun unRegisterSensorListener() {
    mSensorManager.unregisterListener(this, mSensor)
  }

  fun setCurrentMarker(marker: Marker?) {
    mMarker = marker
  }

  override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
    // TODO Auto-generated method stub
  }

  override fun onSensorChanged(event: SensorEvent) {
    if (System.currentTimeMillis() - lastTime < TIME_SENSOR) {
      return
    }
    when (event.sensor.type) {
      Sensor.TYPE_ORIENTATION -> {
        var x = event.values[0]
        x += getScreenRotationOnPhone(mContext).toFloat()
        x %= 360.0f
        if (x > 180.0f) x -= 360.0f else if (x < -180.0f) x += 360.0f
        if (abs(mAngle - x) < 3.0f) {
         return
        }
        mAngle = if (java.lang.Float.isNaN(x)) 0F else x
        if (mMarker != null) {
          mMarker!!.rotation = 360 - mAngle
        }
        lastTime = System.currentTimeMillis()
      }
    }
  }

  companion object {
    /**
     * 获取当前屏幕旋转角度
     *
     * @param context
     * @return 0表示是竖屏; 90表示是左横屏; 180表示是反向竖屏; 270表示是右横屏
     */
    fun getScreenRotationOnPhone(context: Context): Int {
      val display: Display = (context
        .getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay
      when (display.rotation) {
        Surface.ROTATION_0 -> return 0
        Surface.ROTATION_90 -> return 90
        Surface.ROTATION_180 -> return 180
        Surface.ROTATION_270 -> return -90
      }
      return 0
    }
  }
}